<?php
include("../models/entities/class.AccountEntity.php");
@session_start();
if(isset($_SESSION["Username"]))
{
    include("../models/webconfig.php");
    include("../models/class.connection.php");
    include("../models/entities/class.ProductEntity.php");
    include("../models/repositories/class.ProductRepository.php");
    include("../models/entities/class.CategoryEntity.php");
    include("../models/repositories/class.CategoryRepository.php");
    include("../models/entities/class.SectionEntity.php");
    include("../models/repositories/class.SectionRepository.php");
    include("../library/library.pager.php");
    
    include("../models/repositories/class.GroupAuthorityRepository.php");
    if(isset($_SESSION['Account'])){
        $groupAuthorityRepository = new GroupAuthorityRepository();
        $account = $_SESSION['Account'];
        if(!$groupAuthorityRepository->CheckExistGroupAuthority($account->GroupID_i, 2))
            header("location:NoAccess.php");
    }
    else
    {
        header("location:NoAccess.php");
    }
    
    $productRepository = new ProductRepository();
    $categoryRepository = new CategoryRepository();
    $sectionRepository = new SectionRepository();
    $arrSection = $sectionRepository->GetAll();
    $product = null;
    if(isset($_GET['code'])){
        $product = $productRepository->GetProduct($_GET['code']);
        if($product == null){
            exit("Không tìm thấy sản phẩm cần chỉnh sửa");
        }
    }
    else{
        exit("Không tìm thấy sản phẩm cần chỉnh sửa");
    }
    $category = $categoryRepository->GetCategory($product->CategoryID_i);
    function GetListProductImages($imgSrc)
    {
        if(isset($imgSrc))
        {
            if ($imgSrc != "")
            {
                return explode("|", $imgSrc);
            }
        }
        return null;
    }
    
    function CheckExist($str, $arrStr){
        foreach($arrStr as $s){
            if($s == $str) return true;
        }
        return false;
    }
    $arrImages = GetListProductImages($product->ImageSrc_s);
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Product Manager</title>
<link href="../content/Layout.css" rel="stylesheet" type="text/css" media="screen"/>
<link href="../content/ui-lightness/jquery-ui-1.8.6.custom.css" rel="stylesheet" type="text/css" media="screen"/>
<script type="text/javascript" src="../scripts/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="../scripts/jquery.validate.js"></script>
<script type="text/javascript" src="../scripts/jquery-ui-1.8.6.custom.min.js"></script>
<script type="text/javascript" src="../scripts/adminproduct.js">
</script>
<script type="text/javascript">
    $(document).ready(function () {
        var str = location.href.toLowerCase();

        $('ul#mainNav li a').each(function () {
            if (str.indexOf($(this).attr("href").toLowerCase()) > -1)
             $(this).addClass("active");
        });

        $('ul#sideNav li a').each(function () {
            if (str.indexOf($(this).attr("href").toLowerCase()) > -1)
            $(this).addClass("active");
        });
        
        EditProduct.init();
    });   
</script>
<script type="text/javascript" src="../scripts/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
	tinyMCE.init({
		mode: "textareas",
		theme: "advanced",
		plugins: "style,iespell,searchreplace,contextmenu,paste,html",
		forced_root_block : false,
		force_br_newlines : true,
		force_p_newlines : false,    
		convert_newlines_to_brs : true,
		width: "250",

		//&nbsp; Theme options #1
		theme_advanced_buttons1: "bold,italic,underline,formatselect,cut,copy,paste,pastetext,pasteword",
		theme_advanced_buttons2: "fontselect,fontsizeselect,|,link,unlink,code",
		theme_advanced_buttons3: "justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist",
		theme_advanced_buttons4: "",

		//Theme options #2
		theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,fontselect,fontsizeselect,|,bullist,numlist,|,cut,copy,paste,pastetext,pasteword,|,forecolor,backcolor",
		theme_advanced_buttons2: "",

		// Align and place toolbar
		theme_advanced_toolbar_location: "top",
		theme_advanced_toolbar_align: "left",
		theme_advanced_resizing: true,
		readonly: false,

		//style
		content_css : "../scripts/tiny_mce/css/CustomCSS.css",
		theme_advanced_font_sizes: "12px,13px,14px,16px,18px,20px",
		font_size_style_values : "12px,13px,14px,16px,18px,20px",
	});
</script>
<style type="text/css">
label.error{
    color:red;
    float:left;
}
</style>
</head>

<body>
    <div id="format">
        <div id="wrapper">
        	<!--Ph?n main menu-->
			<?php
				include("../includes/backend_mainnav.php");
			?>
		
            <div id="containerHolder">
                <div id="container" style="color: #646464;">
                	<!--Ph?n main content vi?t t?i dây-->
                    <h3>Sửa sản phẩm</h3>
                    <div class="clear"></div>
                        <?php
                            if(isset($_POST['Code']))
                            {
                                $code = $_POST['Code'];
                                $name = $_POST['Name'];
                                $categoryID = $_POST['CategoryID'];
                                $color = $_POST['Color'];
                                $price = $_POST['Price'];
                                $description = $_POST['Description'];
                                $imageSrc = $product->ImageSrc_s;
                                $arrCurImageSrc = explode("|", $imageSrc);
                                $arrImageSrcDeleted = explode("|", $_POST['ImageSrcDeleted']);
                                $imageSrc = "";
                                foreach($arrCurImageSrc as $curImageSrc){
                                    if(!CheckExist($curImageSrc, $arrImageSrcDeleted))
                                    {
                                        $imageSrc .= $curImageSrc . "|";
                                    }
                                }
                                
                                for($i = 0; $i < count($_FILES['image']['name']); $i++)
                                {
                                    $fileSize = $_FILES['image']['size'][$i];
                                    if($fileSize > 0)
                                    {
                                        $fileType = $_FILES['image']['type'][$i];
                                        if($fileType == "image/x-png" || $fileType == "image/png" || $fileType == "image/gif"
				                            || $fileType == "image/pjpeg" || $fileType == "image/jpeg" && $fileSize < 2097152)
                                        {
                                            if($i == count($_FILES['image']['name']) - 1){
                                                $imageSrc .= $_FILES['image']['name'][$i];
                                            }
                                            else{
                                                $imageSrc .= $_FILES['image']['name'][$i] . "|";
                                            }
                                        }
                                    }
                                }
                                if($imageSrc[strlen($imageSrc) - 1] == "|")
                                {
                                    $imageSrc = substr($imageSrc, 0, strlen($imageSrc) - 1);
                                }
                               
                                $entity = new ProductEntity($code, $name, $description, $imageSrc, $color, "", $price, 0, $categoryID);
                                if($productRepository->Update($entity) > 0)
                                {
                                    foreach($arrImageSrcDeleted as $imgDelete){
                                        if($imgDelete != ""){
                                            if(file_exists("../content/images/Products/" . $code . "/" . $imgDelete) == true){
                                                fopen("../content/images/Products/" . $code . "/" . $imgDelete, "w");
                                                unlink("../content/images/Products/" . $code . "/" . $imgDelete);
                                            }
                                        }
                                    }
                                    for($i = 0; $i < count($_FILES['image']['name']); $i++)
                                    {
                                        $fileSize = $_FILES['image']['size'][$i];
                                        if($fileSize > 0)
                                        {
                                            $fileType = $_FILES['image']['type'][$i];
                                            if($fileType == "image/x-png" || $fileType == "image/png" || $fileType == "image/gif"
    				                            || $fileType == "image/pjpeg" || $fileType == "image/jpeg" && $fileSize < 2097152)
                                            {
                                                if($_FILES['image']['error'][$i] > 0)
                                                {
                                                	echo "ERROR: " . $_FILES['image']['error'][$i] . "<br/>";
                                                }
                                                else
                                                {
                                            		move_uploaded_file($_FILES['image']['tmp_name'][$i], "../content/images/Products/" . $code . "/" . $_FILES['image']['name'][$i]);
                                                }
                                            }
                                            else
                                            {
                                                echo "<br/> File không đúng định dạng hoặc quá kích thước cho phép";
                                            }
                                        }
                                    }
                                    echo "<br/> Sửa sản phẩm thành công";
                                    $product = $productRepository->GetProduct($code);
                                    $category = $categoryRepository->GetCategory($categoryID);
                                    $arrImages = GetListProductImages($imageSrc);
                                }
                                else
                                {
                                    echo "<br/> Có lỗi xảy ra khi sửa sản phẩm ! Hãy thử lại";
                                }
                            }                             
                        ?>
                    <script type="text/javascript">
                        $(document).ready(function () {
                            EditProduct.LoadColor("<?php echo $product->Color_s; ?>");
                        });
                    </script>
                    <fieldset style="background: none; margin:20px auto 0 auto; width: 100%;">
                        <form method="post" id="frmProduct" enctype="multipart/form-data">
                            <div style="float: left; width:150px; text-align: left;">Mã sản phẩm</div>
                            <div style="float: left; text-align: left;"><input type="text" readonly="true" id="Code" name="Code" style="background-color: #dedede; width: 200px;" value="<?php echo $product->Code_s; ?>" /></div>
                            <div class="clear"></div>
                            <div style="float: left; width:150px; text-align: left; margin-top:7px;">Tên sản phẩm</div>
                            <div style="float: left; text-align: left; margin-top:7px; width:250px;"><input class="required" type="text" id="Name" name="Name" style="width: 200px;" value="<?php echo $product->Name_s; ?>" /></div>
                            <div class="clear"></div>
                            <div style="float: left; width:150px; text-align: left; margin-top:7px;">Section</div>
                            <div style="float: left; text-align: left; margin-top:7px;">
                                <select name="SectionID" id="SectionID">
                                    <?php
                                        foreach($arrSection as $section){
                                    ?>
                                    <option value="<?php echo $section->ID_i; ?>"><?php echo $section->Name_s; ?></option>      
                                        <?php
                                        }
                                    ?>
                                </select>
                            </div>
                            <div class="clear"></div>
                            <div style="float: left; width:150px; text-align: left; margin-top:7px;">Category</div>
                            <div style="float: left; text-align: left; margin-top:7px;">
                                <select name="CategoryID" id="CategoryID">
                                   
                                </select>
                            </div>
                            <script type="text/javascript">
                                EditProduct.LoadSection_Category(<?php echo $category->SectionID_i; ?>, <?php echo $category->ID_i; ?>);
                            </script>
                            <div class="clear"></div>
                            <div style="float: left; width:150px; text-align: left; margin-top:7px;">Màu sắc</div>
                            <div style="float: left; text-align: left; margin-top:7px;">
                                <?php
                                    include("../includes/colorBar.php");
                                ?>
                                <input type="text" name="Color" style="display:none;" />
                            </div>
                            <div class="clear"></div>
                            <div style="float: left; width:150px; text-align: left; margin-top:7px;">Giá</div>
                            <div style="float: left; text-align: left; margin-top:7px;;">
                                <input class="required" type="text" name="Price" style="width: 100px;" value="<?php echo ($product->Price_f); ?>"/>&nbsp; <span style="font-weight: bold;">VNĐ</span>
                            </div>
                            <div class="clear"></div>
                            <div style="float: left; width:150px; text-align: left; margin-top:7px;">Mô tả</div>
                            <div style="float: left; text-align: left; margin-top:7px;">
                                <textarea style="width: 200px; height:150px;" name="Description"><?php echo $product->Description_s; ?></textarea>
                            </div>
                            <div class="clear"></div>
                            <div style="float: left; width:150px; text-align: left; margin-top:7px;">Hình ảnh</div>
                            <div style="float: left; text-align: left; margin-top:7px;">
                                <table style="width: 400px; border: 1px solid #d1d1d1; text-align:center; font-family: tahoma; font-size:13px;">
                                    <tr style="font-weight: bold; border: 1px solid #d1d1d1;">
                                        <td style="border: 1px solid #d1d1d1; color:#f47a0e;padding-top:5px; padding-bottom:5px; width:70px;">STT</td>
                                        <td style="border: 1px solid #d1d1d1; color:#f47a0e;padding-top:5px; padding-bottom:5px; width:260px;">Hình ảnh</td>
                                        <td style="border: 1px solid #d1d1d1; color:#f47a0e;padding-top:5px; padding-bottom:5px; width:70px;"></td>
                                    </tr>
                                    <?php
                                        if(isset($arrImages))
                                        {
                                            for($i = 0; $i < count($arrImages); $i++){
                                    ?>
                                    <tr style="font-weight: bold;">
                                        <td style="border: 1px solid #d1d1d1; width:70px;"><?php echo ($i + 1); ?></td>
                                        <td style="text-align:center;border: 1px solid #d1d1d1; width:260px;">
                                            <img style="max-width: 100px;" src="../content/images/Products/<?php echo $product->Code_s . '/' . $arrImages[$i] ?>" style="max-height: 120px; max-width: 120px; border: 1px solid #d1d1d1;" />
                                        </td>
                                        <td style="text-align:center;border: 1px solid #d1d1d1;width:70px;"><a class="delImage" href="#" onclick="return false;" imgSrc="<?php echo $arrImages[$i]; ?>">Xóa</a></td>
                                    </tr>               
                                    <?php
                                            }
                                        }
                                    ?>
                                </table>
                                <input type="text" name="ImageSrcDeleted" style="display: none;" />
                            </div>
                            <div class="clear"></div>
                            <div style="float: left; width:150px; text-align: left; margin-top:7px;"></div>
                            <div id="fileContain" style="float: left; text-align: left; margin-top:7px;">
                                <input type="file" name="image[]" />&nbsp;
                                <input type="button" id="btnAddFile" value="Thêm hình ảnh"/> <span style="color: red;">Chỉ chấp nhận .jpg, .gif, .png và có dụng lượng &lt;= 2MB</span>
                            </div>
                            <div class="clear"></div>
                            <div style="float: left; width:150px; text-align: left; margin-top:7px;"></div>
                            <div style="float: left; text-align: left; margin-top:7px;">
                                <input type="submit" value="Sửa" style="width:70px;"/>
                            </div>
                        </form>
                        
                    </fieldset> 
                 </div>
            <!-- // #container -->
            
            <!--Ph?n footer c?a trang-->
            <?php
            include("../includes/backend_footer.php");
            ?>
            </div>
        </div>
</body>

</html>
<?php
}
else
{
    header("location:../views/Admin_login.php?logout=TRUE");
}
?>